package com.yzt.zhuju.mvp;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.CallSuper;

import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.dialog.LoadingDialog;
import com.yzt.zhuju.rx.ActivityEvent;
import com.yzt.zhuju.rx.LifecycleTransformer;
import com.yzt.zhuju.rx.RxUtils;
import com.yzt.zhuju.utils.ReflectUtils;
import com.yzt.p_base.utils.ToastUtil;

import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

public abstract class MVPActivity<P extends BasePresenter> extends BaseActivity implements Contract.IView {

    private final Subject<Integer> lifecycleSubject = PublishSubject.create();

    protected P mPresenter;

    protected LoadingDialog mDialog;

    @CallSuper
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mDialog = new LoadingDialog(this);
        Class<P> presenter = ReflectUtils.getT(getClass(), 0);
        if (presenter != null) {
            try {
                mPresenter = presenter.newInstance();
                mPresenter.attach(this);
            } catch (Exception e) {

            }
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.ON_DESTORY);
        if (null != mPresenter) {
            mPresenter.detach();
        }
        super.onDestroy();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void close() {
        finish();
    }

    @Override
    public void closeImmediately() {
        finish();
    }

    @Override
    public void showToast(String tip) {
        ToastUtil.showMessage(tip);
    }

    @Override
    public void showLoadingDialog(String tip) {
        mDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        mDialog.dismiss();
    }

    @Override
    public void showErrorToast(String tip) {
        ToastUtil.showMessage(tip);
    }

    @Override
    public <T> LifecycleTransformer<T> bindLifecycle(int event) {
        return RxUtils.bindLifecycle(lifecycleSubject, event);
    }

    @Override
    public <T> LifecycleTransformer<T> bindOnDestroy() {
        return RxUtils.bindLifecycle(lifecycleSubject, ActivityEvent.ON_DESTORY);
    }
}